import { mapGetters, mapMutations, mapActions } from 'vuex'
import { shuffle } from 'common/js/tool'
import { playMode } from 'common/js/config'
import * as types from '@/store/mutations-types'
import * as _ from 'lodash'

export const playlistMixin = {
  computed: {
    ...mapGetters([
      'playlist'
    ])
  },
  mounted() {
    this.handlePlaylist(this.playlist)
  },
  activated() {
    this.handlePlaylist(this.playlist)
  },
  watch: {
    playlist(newVal) {
      this.handlePlaylist(newVal)
    }
  },
  methods: {
    handlePlaylist() {
      throw new Error('component must implement handlePlaylist method')
    },
    ...mapMutations({
      setPlayMode: types.SET_PLAY_MODE,
      setCurrentIndex: types.SET_CURRENT_INDEX,
      setPlayList: types.SET_PLAYLIST
    })
  }
}

export const mixinPlayMode = {
  methods: {
    getFavoriteIcon(song) {
      return this.isFavorite(song) ? 'icon-favorite' : 'icon-not-favorite'
    },
    isFavorite(song) {
      let ind = _.findIndex(this.favoriteList, (o) => {
        return song.mid === o.mid
      })
      return ind > -1
    },
    toggleFavorite(song) {
      if (this.isFavorite(song)) {
        this.deleteFavoriteList(song)
      } else {
        this.saveFavoriteList(song)
      }
    },
    changePlayMode() {
      let newMode = (this.mode + 1) % 3
      this.setPlayMode(newMode)
      if (playMode.random === newMode) {
        let currentSongId = this.currentSong.id
        const newPlayinglist = shuffle(this.sequenceList)
        this.setPlayList(newPlayinglist)
        let newCurrentIndex = _.findIndex(newPlayinglist, function(o) { return o.id === currentSongId })
        this.setCurrentIndex(newCurrentIndex)
      }
    },
    ...mapMutations({
      setPlayMode: 'SET_PLAY_MODE',
      setPlayList: 'SET_PLAYLIST',
      setSequenceList: 'SET_SEQUENCE_LIST',
      setCurrentIndex: 'SET_CURRENT_INDEX'
    }),
    ...mapActions({
      'saveFavoriteList': 'saveFavoriteList',
      'deleteFavoriteList': 'deleteFavoriteList'
    })
  },
  computed: {

    modeIcon() {
      return this.mode === playMode.sequence ? 'icon-sequence' : this.mode === playMode.loop ? 'icon-loop' : 'icon-random'
    },
    ...mapGetters({
      playlist: 'playlist',
      sequenceList: 'sequenceList',
      currentSong: 'currentSong',
      currentIndex: 'currentIndex',
      mode: 'mode',
      favoriteList: 'favoriteList'
    })
  }
}

export const searchMixin = {
  data() {
    return {
      query: '',
      delayTime: 120
    }
  },
  computed: {
    ...mapGetters({
      searchHistory: 'searchHistory'
    })
  },
  methods: {
    handleBeforScroll() {
      this.$refs.searchBox.doBlur()
    },
    handleQuery(query) {
      this.query = query
    },
    addQuery() {
      this.saveSearchHistory(this.query)
    },
    ...mapActions({
      saveSearchHistory: 'saveSearchHistory',
      deleteSearchHistory: 'deleteSearchHistory',
      clearSearchHistory: 'clearSearchHistory'
    })
  }
}
